package redisson.rest;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

import org.redisson.api.RAtomicLong;
import org.redisson.api.RTimeSeries;
import org.redisson.api.RedissonClient;
import org.redisson.api.TimeSeriesEntry;
import org.redisson.codec.JsonJacksonCodec;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;

import lombok.extern.slf4j.Slf4j;

@Slf4j
//@RestController
//@RequestMapping("/time-series")
@EnableScheduling
public class TimeSeriesController implements SmartInitializingSingleton {

	static Random random = new Random();

	@Autowired
	RedissonClient redissonClient;

	@GetMapping("/next")
	public String next() {

		String now = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
		RAtomicLong atomicLong = redissonClient.getAtomicLong("global:" + now);

		int count = random.nextInt(999);
		log.info("### 产生count -> {} ", count);
		for (int i = 0; i < count; i++) {
			atomicLong.incrementAndGet();
		}
		return String.valueOf(atomicLong.get());
	}

	@Override
	public void afterSingletonsInstantiated() {

		/* 1. 获取时间序列实例（值用 Double，标签用 String） */
		RTimeSeries<Double, String> ts = redissonClient.getTimeSeries("rpa:probe", JsonJacksonCodec.INSTANCE);

		/* 2. 写入 10 条数据（每秒 1 条） */
		long now = System.currentTimeMillis();
		for (int i = 0; i < 10; i++) {
			ts.add(now + i * 1000, 20 + Math.random() * 10, "host-A");
		}

		Collection<TimeSeriesEntry<Double, String>> pollLastEntries = ts.pollLastEntries(5);

		Collection<Double> pollLast = ts.pollLast(5);

		System.out.println("");

	}

	@Scheduled(cron = "* * * * * *")
	public void scheduler() {

		RTimeSeries<Map<String, String>, String> ts = redissonClient.getTimeSeries("rpa:probe",
				JsonJacksonCodec.INSTANCE);

		ThreadLocalRandom r = ThreadLocalRandom.current();
		int nextInt = r.nextInt(5, 10);

		for (int i = 0; i < nextInt; i++) {
			Map<String, String> map = new HashMap<>();
			map.put("success", String.valueOf(r.nextBoolean()));
			map.put("province", String.valueOf(r.nextInt(1, 36)));
			map.put("type", String.valueOf(r.nextInt(1, 3)));
			ts.add(System.currentTimeMillis(), map);
		}

//		log.info("### mock 产生数据 {} 条", nextInt);

	}

}
